//
//  NewMarketWebViewController.m
//  HCNewGoldFinger
//
//  Created by 刘琛 on 2019/4/9.
//  Copyright © 2019年 zjhcsoftios. All rights reserved.
//

#import "NewMarketWebViewController.h"
#import <WebKit/WebKit.h>
#import "MJExtension.h"
#import "NewMarketWebJSModel.h"
#import <MessageUI/MessageUI.h>
#import "UIViewController+BackButtonHandler.h"
#import <SDWebImage/UIButton+WebCache.h>
#import <AFNetworking/AFNetworking.h>
#import "ZYQAssetPickerController.h"
#import "UIBarButtonItem+BlocksKit.h"
#import "NetworkAddress.h"
#import "SVProgressHUD.h"
#import <Photos/Photos.h>
#import <HXPhotoPicker/HXPhotoPicker.h>
#import "UIColor+EX.h"
#import "ISeeUserInfoModel.h"
#import <YYModel/YYModel.h>

#define iSEESCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define iSEESCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface NewMarketWebViewController ()<WKScriptMessageHandler,WKUIDelegate,WKNavigationDelegate,MFMessageComposeViewControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,HXCustomNavigationControllerDelegate>

@property (nonatomic, strong) NSString *leftBarItemGobackMethod;

@property (nonatomic, strong) NSString *rightBarItemMethod;

@property (nonatomic, strong) NSString *closeCallBackMethod;

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@property (nonatomic, strong) NewMarketWebJSModel *uploadModel;

@property (nonatomic, strong) HXPhotoManager *photoManager;
@property (nonatomic, assign) NSInteger photoDownloadCount;
@property (nonatomic, strong) NSMutableArray *photoUploadArray;

@end

@implementation NewMarketWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _manager = [AFHTTPSessionManager manager];
    _manager.responseSerializer = [AFJSONResponseSerializer serializer];
    _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",nil];
    _photoUploadArray = [NSMutableArray array];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    if (!self.enterType) {
        self.enterType = 1;
        
    }
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] bk_initWithImage:[UIImage imageNamed:@"Back Chevron"] style:UIBarButtonItemStylePlain handler:^(id sender) {
        
        if (self.leftBarItemGobackMethod.length > 0) {
            [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@()", self.leftBarItemGobackMethod] completionHandler:nil];
            self.leftBarItemGobackMethod = @"";
        }else {
            
            if ([self.webView canGoBack]) {
                [self.webView goBack];
            }else {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
        
    }];
    
    
    
    if (self.enterType == 2) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] bk_initWithTitle:@"关闭" style:UIBarButtonItemStylePlain handler:^(id sender) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
    }


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark webDelegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    
    //处理tel标签拦截
    if ([scheme isEqualToString:@"tel"]) {
        NSString *resourceSpecifier = [URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
        /// 防止iOS 10及其之后，拨打电话系统弹出框延迟出现
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        });
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    if (self.method.length > 0) {
        [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@()", self.method] completionHandler:nil];
        self.method = @"";
    }
}

#pragma mark 网页JS调用

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    if ([message.name isEqualToString:@"iSee"]) {
        [self getMessageInfo:message.body];
    }
}

- (void)getMessageInfo:(id) body {
    
    NewMarketWebJSModel *model = [NewMarketWebJSModel mj_objectWithKeyValues:body];
    
    if ([model.callback isEqualToString:@"pageStart"]) {
        //重新加载页面
        self.navigationItem.rightBarButtonItem = nil;
        self.leftBarItemGobackMethod = @"";
    }else if ([model.callback isEqualToString:@"setTitle"]) {
        //设置标题
        self.title = model.body.title;
    }else if ([model.callback isEqualToString:@"sendMsg"]) {
        [self sendTextMessage:model];
    }else if ([model.callback isEqualToString:@"headMoreText"]){
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:model.body.title style:UIBarButtonItemStylePlain target:self action:@selector(rightBarItemButtonAction)];
        self.rightBarItemMethod = model.body.method;
    }else if ([model.callback isEqualToString:@"headMoreMsg"]) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
        [button sd_setImageWithURL:[NSURL URLWithString:model.body.url] forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
        [button addTarget:self action:@selector(rightBarItemButtonAction) forControlEvents:UIControlEventTouchUpInside];
        self.rightBarItemMethod = model.body.method;
    }else if ([model.callback isEqualToString:@"openNewWindow"]) {
        NewMarketWebViewController *web = [[NewMarketWebViewController alloc] init];
        web.loadUrl = model.body.url;
        [self.navigationController pushViewController:web animated:YES];
    }else if ([model.callback isEqualToString:@"openCloseWindow"]) {
        self.closeCallBackMethod = model.body.method;
        NewMarketWebViewController *web = [[NewMarketWebViewController alloc] init];
        web.enterType = 2;
        web.loadUrl = model.body.url;
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:web];
        [nav.navigationBar setBackgroundImage:[self imageFromColor:[UIColor colorWithHexString:@"169BD5"] size:CGSizeMake(kScreenWidth, Height_NavBar)] forBarMetrics:UIBarMetricsDefault];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:nav animated:YES completion:^{
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCallBackNote:) name:@"RECEVIECALLBACKINFO" object:nil];
        }];
    }else if ([model.callback isEqualToString:@"openCallBack"]) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
        NSString *str = [model mj_JSONString];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"RECEVIECALLBACKINFO" object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys: str, @"body", nil]];
    }else if ([model.callback isEqualToString:@"openImage"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"图片上传" message:@"请选择图片来源" preferredStyle:UIAlertControllerStyleActionSheet];
        self.uploadModel = model;
        if ([model.body.type integerValue] == 1) {
            [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                [self openCamera];
                
            }]];
        }else if ([model.body.type integerValue] == 2) {
            [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self openAlbum];
            }]];
        }else if ([model.body.type integerValue] == 3) {
            [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self openCamera];
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self openAlbum];
            }]];
        }
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
    }else if ([model.callback isEqualToString:@"gobackHome"]) {
        
        ISeeUserInfoModel *userInfo = [ISeeUserInfoModel mj_objectWithKeyValues:[[[NSUserDefaults standardUserDefaults] objectForKey:NMarketUserInfo] mj_JSONObject]];
        if (userInfo.userFlag == 2) {
            
            [self gobackToTheSpecifiedPage:@"HCNewMainViewCtrl"];
            
        }else {
        
            [self gobackToTheSpecifiedPage:@"NewLoveMarketingHomewController"];
        }
        
    }else if ([model.callback isEqualToString:@"gobackOrderlist"]) {
        
        [self gobackToTheSpecifiedPage:@"NewMissonListController"];
    }else if ([model.callback isEqualToString:@"goBack"]) {
        self.leftBarItemGobackMethod = model.body.method;
    }
}


#pragma mark 图片上传

- (void)openCamera{

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:picker animated:YES completion:nil];
    }else {
        [SVProgressHUD showErrorWithStatus:@"当前设备不支持相机"];
    }
    
}

- (void)openAlbum {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        [self selectPictures:[_uploadModel.body.count integerValue]];
    }else {
        [SVProgressHUD showErrorWithStatus:@"当前相册"];
    }
}


//相机上传
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //UIImagePickerControllerOriginalImage
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *selectedImage = info[@"UIImagePickerControllerOriginalImage"];
    [self loadImageFinished:selectedImage];
    [self uploadImages:@[selectedImage]];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

//保存图片到图库
- (void)loadImageFinished:(UIImage *)image
{
    __block NSString *createdAssetID =nil;
    NSError *error =nil;
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        createdAssetID = [PHAssetChangeRequest            creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
    } error:&error];
}


//相册上传
- (void)selectPictures:(NSInteger ) maxCount
{
    
    self.photoManager.configuration.photoMaxNum = maxCount;
    [self.photoManager clearSelectedList];
    HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithManager:self.photoManager delegate:self];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:nav animated:YES completion:nil];
    
  
}

- (void)photoNavigationViewController:(HXCustomNavigationController *)photoNavigationViewController didDoneAllList:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photoList videos:(NSArray<HXPhotoModel *> *)videoList original:(BOOL)original {
    
    [_photoUploadArray removeAllObjects];
    
    _photoDownloadCount = photoList.count;
    
    for (HXPhotoModel *model in photoList) {
        [model requestPreviewImageWithSize:PHImageManagerMaximumSize startRequestICloud:^(PHImageRequestID iCloudRequestId, HXPhotoModel *model) {
            // 如果照片在iCloud上会去下载,此回调代表开始下载iCloud上的照片
            // 如果照片在本地存在此回调则不会走
        } progressHandler:^(double progress, HXPhotoModel *model) {
            // iCloud下载进度
            // 如果为网络图片,则是网络图片的下载进度
        } success:^(UIImage *image, HXPhotoModel *model, NSDictionary *info) {
            
            [_photoUploadArray addObject:image];
            
            self.photoDownloadCount--;
            
        } failed:^(NSDictionary *info, HXPhotoModel *model) {
            // 获取失败
            self.photoDownloadCount--;
        }];
    }
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [UINavigationBar appearance].translucent = NO;
}

- (void)photoNavigationViewControllerDidCancel:(HXCustomNavigationController *)photoNavigationViewController {
    

    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [UINavigationBar appearance].translucent = NO;
}

- (void)setPhotoDownloadCount:(NSInteger)photoDownloadCount {
    
    _photoDownloadCount = photoDownloadCount;
    
    if (_photoDownloadCount == 0) {
        [self uploadImages:_photoUploadArray];
    }
}



- (void)uploadImages:(NSArray *) images {
    

    [SVProgressHUD showWithStatus:@"图片上传中"];
    
    [_manager POST:self.uploadModel.body.url parameters:self.uploadModel.body.params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (UIImage *image in images) {
            
            NSData *data = [self scaleImage:image toKb:1024];
            [formData appendPartWithFileData:data name:self.uploadModel.body.title fileName:[NSString stringWithFormat:@"image.png"] mimeType:@"image/png"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSMutableDictionary *dic =responseObject;
        if ([dic[@"code"] integerValue] == 200) {
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            
            NSString *str = [dic[@"body"] yy_modelToJSONString];
            NSLog(@"%@", [NSString stringWithFormat:@"%@('%@')", self.uploadModel.body.method, str]);
            [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@('%@')", self.uploadModel.body.method, str] completionHandler:nil];
        }else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", dic[@"msg"]]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}


#pragma mark 现在表单类方法

- (void)getCallBackNote:(NSNotification *)note {
    
    NewMarketWebJSModel *model = [NewMarketWebJSModel mj_objectWithKeyValues:note.userInfo[@"body"]];
    [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@(%@)", model.body.method, model.body.title] completionHandler:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RECEVIECALLBACKINFO" object:nil];
}

#pragma mark 右侧按钮点击事件

- (void)rightBarItemButtonAction {
    [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@()", self.rightBarItemMethod] completionHandler:nil];
}

#pragma mark
- (void)sendTextMessage:(NewMarketWebJSModel *) model {
    if ([MFMessageComposeViewController canSendText]) {
        MFMessageComposeViewController *vc =[[MFMessageComposeViewController alloc] init];
        vc.body = model.body.title;
        vc.recipients = [NSArray arrayWithObject:model.body.method];
        vc.navigationBar.tintColor = [UIColor colorWithRed:0.1877 green:0.5138 blue:0.9837 alpha:1.0];
        [vc setMessageComposeDelegate:self];
        [self  presentViewController:vc animated:YES completion:nil];
    }
}

#pragma mark 发送iMessage代理
//短信控制器处理
-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    
    switch (result) {
        case MessageComposeResultSent:
            //信息传送成功
            
            break;
        case MessageComposeResultFailed:
            //信息传送失败
            
            break;
        case MessageComposeResultCancelled:
            //信息被用户取消传送
            
            break;
        default:
            break;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark json转换
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

- (NSString*)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

#pragma mark 返回前置页面

- (void)gobackToTheSpecifiedPage:(NSString *) className {
    
    NSArray * array = self.navigationController.viewControllers;
    
    for (NSInteger i = array.count-1; i >= 0; i--) {
        UIViewController *ctrl = self.navigationController.viewControllers[i];
        if ([ctrl isKindOfClass:NSClassFromString(className)]) {
            UIViewController *ctrl1 = self.navigationController.viewControllers[i];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADNEWMISSONLIST" object:nil];
            [self.navigationController popToViewController:ctrl1 animated:YES];
            break;
        }
    }
}


#pragma mark 返回按钮事件拦截
- (BOOL)navigationShouldPopOnBackButton {
    if (self.leftBarItemGobackMethod.length > 0) {
        [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@()", self.leftBarItemGobackMethod] completionHandler:nil];
        self.leftBarItemGobackMethod = @"";
        return NO;
    }else {

        if ([self.webView canGoBack]) {
            [self.webView goBack];
            return NO;
        }else {
            return YES;
        }
    }
}

#pragma mark 图片上传压缩
- (NSData *)scaleImage:(UIImage *)image toKb:(NSInteger)kb{
    
    kb*=1024;
    
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > kb && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    NSLog(@"当前大小:%fkb",(float)[imageData length]/1024.0f);
    return imageData;
    
}

#pragma mark 生成图片
- (UIImage*)imageFromColor:(UIColor*)color size:(CGSize)size
{
    CGRect rect=CGRectMake(0.0f, 0.0f, size.width,size.height);
    UIGraphicsBeginImageContext(size);//创建图片
    CGContextRef context = UIGraphicsGetCurrentContext();//创建图片上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);//设置当前填充颜色的图形上下文
    CGContextFillRect(context, rect);//填充颜色
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

#pragma mark 懒加载
- (HXPhotoManager *)photoManager {
    if (!_photoManager) {
        _photoManager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
        _photoManager.type = HXPhotoManagerSelectedTypePhoto;
    }
    return _photoManager;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
